<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>摄像头切换与拍照功能</title>
    <style>
        body { font-family: Arial; text-align: center; margin: 20px }
        .camera-container { position: relative; display: inline-block }
        video { width: 100%; max-width: 640px; background: #000; border-radius: 8px }
        canvas { display: none } /* 隐藏canvas元素 */
        .controls { margin: 15px 0 }
        button { padding: 10px 20px; margin: 5px; cursor: pointer; border: none; border-radius: 4px }
        #captureBtn { background: #4CAF50; color: white }
        #switchBtn { background: #2196F3; color: white }
        #stopBtn { background: #f44336; color: white }
        select { padding: 8px; margin: 10px; width: 200px }
        .photos { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; margin-top: 20px }
        .photo-item { width: 150px; border: 1px solid #ddd; border-radius: 4px }
    </style>
</head>
<body>
    <h1>摄像头切换与拍照功能</h1>
    
    <div class="camera-container">
        <video id="video" autoplay playsinline></video>
        <canvas id="canvas"></canvas>
    </div>
    
    <div class="controls">
        <select id="cameraSelect"></select>
        <button id="switchBtn">切换前后置</button>
        <button id="captureBtn">拍照</button>
        <button id="stopBtn">停止摄像头</button>
    </div>
    
    <div class="photos" id="photoGallery"></div>

    <script>
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const cameraSelect = document.getElementById('cameraSelect');
        const switchBtn = document.getElementById('switchBtn');
        const captureBtn = document.getElementById('captureBtn');
        const stopBtn = document.getElementById('stopBtn');
        const photoGallery = document.getElementById('photoGallery');
        
        let currentStream = null;
        let usingFrontCamera = true;
        let photoCount = 0;

        // 获取设备列表
        async function getDevices() {
            try {
                const devices = await navigator.mediaDevices.enumerateDevices();
                const videoDevices = devices.filter(device => device.kind === 'videoinput');
                
                cameraSelect.innerHTML = videoDevices
                    .map(device => `<option value="${device.deviceId}">${device.label || '摄像头'}</option>`)
                    .join('');
            } catch (err) {
                console.error("设备枚举错误:", err);
            }
        }

        // 启动指定摄像头
        async function startCamera(deviceId) {
            if (currentStream) {
                currentStream.getTracks().forEach(track => track.stop());
            }
            
            const constraints = {
                video: {
                    deviceId: deviceId ? { exact: deviceId } : undefined,
                    facingMode: usingFrontCamera ? "user" : { exact: "environment" },
                    width: { ideal: 1280 },
                    height: { ideal: 720 }
                }
            };

            try {
                currentStream = await navigator.mediaDevices.getUserMedia(constraints);
                video.srcObject = currentStream;
                
                // 设置canvas尺寸与视频相同
                video.onloadedmetadata = () => {
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                };
                
                if (!deviceId) getDevices();
            } catch (err) {
                console.error("摄像头错误:", err);
                alert(`摄像头访问失败: ${err.message}`);
            }
        }

        // 切换前后置摄像头
        function switchCamera() {
            usingFrontCamera = !usingFrontCamera;
            startCamera();
        }

        // 停止摄像头
        function stopCamera() {
            if (currentStream) {
                currentStream.getTracks().forEach(track => track.stop());
                video.srcObject = null;
                currentStream = null;
            }
        }

        // 拍照功能
        function capturePhoto() {
            if (!currentStream) {
                alert('请先开启摄像头');
                return;
            }

            // 绘制当前视频帧到canvas:ml-citation{ref="7,8" data="citationList"}
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            // 创建照片元素并添加到相册:ml-citation{ref="2,9" data="citationList"}
            const dataUrl = canvas.toDataURL('image/jpeg', 0.9);
            photoCount++;
            
            const photoItem = document.createElement('div');
            photoItem.className = 'photo-item';
            photoItem.innerHTML = `
                <img src="${dataUrl}" alt="照片 ${photoCount}" style="width:100%">
                <div>照片 ${photoCount}<br>${new Date().toLocaleTimeString()}</div>
            `;
            
            photoGallery.appendChild(photoItem);
        }

        // 设备选择变化时
        cameraSelect.addEventListener('change', () => {
            startCamera(cameraSelect.value);
        });

        // 按钮事件绑定
        switchBtn.addEventListener('click', switchCamera);
        captureBtn.addEventListener('click', capturePhoto);
        stopBtn.addEventListener('click', stopCamera);

        // 初始化
        getDevices();
        startCamera();
    </script>
</body>
</html>
